#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH


#----------------------------------------------------------Configuration information-----------------------------------------------------------
# Download Link of node
node_down_link="https://npmmirror.com/mirrors/node/v16.13.1/node-v16.13.1-linux-x64.tar.xz"

# Download Link of jq
jq_down_link="https://gitee.com/photo-of-xiyin/jq.git"

base_folder=/usr/local

# note Synchronous directory
note_sync_dir="$base_folder/.sync_note"

# web-cli
webdav_log_file="$base_folder/node/webdav_cli.log"
default_webdav_port=1900
webdav_rigts="all"
webdav_config_file="$base_folder/node/webdav_cli.json"

#jq
jq_folder="${base_folder}/jq"
jq_file="${jq_folder}/jq"

Green_font_prefix="\033[32m"
Red_font_prefix="\033[31m"
Green_background_prefix="\033[42;37m"
Red_background_prefix="\033[41;37m"
Font_color_suffix="\033[0m"

Info="${Green_font_prefix}[信息]${Font_color_suffix}"

Error="${Red_font_prefix}[错误]${Font_color_suffix}"

Tip="${Green_font_prefix}[注意]${Font_color_suffix}"
full_line="————————————————————————————————————————————"

#----------------------------------------------------------Configuration information-----------------------------------------------------------


function install_and_start_webdav() {
	set_username_and_pwd
	set_webdav_port

	# install node
	wget $node_down_link -O $base_folder/node.tar.xz
	mkdir -p $base_folder/node &
	tar xvfJ $base_folder/node.tar.xz -C $base_folder/node --strip-components 1

	# Add soft link
	ln -s $base_folder/node/bin/node /usr/bin/node

	# install webdav-cli
	$base_folder/node/bin/npm install --global webdav-cli

	get_public_ip
	get_private_ip
	write_webdav_config

	# run webdav-cli
	start_webdav

	stop_firewall
	view_webdav_cofig

}

#
function write_webdav_config() {

	echo -e "${Info} ${full_line}开始写入webdav-cli配置信息${full_line}" && echo

	cat >${webdav_config_file} <<-EOF
		{
		"public_ip": "${public_ip}",
		"private_ip": "${private_ip}",
		"webdav_port": ${webdav_port},
		"webdav_user": "${webdav_user}",
		"webdav_pwd": "${webdav_pwd}",
		"other": "other"
		}
	EOF
	[[ ! -e $webdav_config_file ]] && echo -e "${Error}：配置信息写入失败" && break
	echo -e "${Info} ${full_line}webdav-cli配置信息写入成功！${full_line}" && echo
}

function check_webdav_cli_installtation_status() {

	[[ ! -e "${base_folder}/node" ]] || [[ ! -e $webdav_config_file ]] && echo -e "${Error}：请先安装webdav-cli  ${Font_color_suffix}" && exit 1

}

function modify_webdav_config() {
	check_webdav_cli_installtation_status
	get_webdav_config

	modify_username_and_pwd
	modify_port

	restart_webdav && view_webdav_cofig
}

function modify_port() {
	set_webdav_port
	# echo -e "sed -i 's/"webdav_port": '"$(echo ${webdav_port_from_jq})"'/"webdav_port": '"$(echo ${webdav_port})"'/g' ${webdav_config_file}"
	sed -i 's/"webdav_port": '"$(echo ${webdav_port_from_jq})"'/"webdav_port": '"$(echo ${webdav_port})"'/g' ${webdav_config_file}
}

function modify_username_and_pwd() {
	set_username_and_pwd
	# echo -e　"sed -i 's/"webdav_user": "'"$(echo ${webdav_user_from_jq})"'"/"webdav_user": "'"$(echo ${webdav_user})"'"/g' ${webdav_config_file"
	sed -i 's/"webdav_user": "'"$(echo ${webdav_user_from_jq})"'"/"webdav_user": "'"$(echo ${webdav_user})"'"/g' ${webdav_config_file}

	# echo -e  "sed -i 's/"webdav_pwd": "'"$(echo ${webdav_pwd_from_jq})"'"/"webdav_pwd": "'"$(echo ${webdav_pwd})"'"/g' ${webdav_config_file}"
	sed -i 's/"webdav_pwd": "'"$(echo ${webdav_pwd_from_jq})"'"/"webdav_pwd": "'"$(echo ${webdav_pwd})"'"/g' ${webdav_config_file}
}

# check root
check_root() {
	[[ $EUID != 0 ]] && echo -e "${Error} 当前账号非ROOT(或没有ROOT权限)，无法继续操作，请使用${Green_background_prefix} sudo su ${Font_color_suffix}来获取临时ROOT权限（执行后会提示输入当前账号的密码）。" && exit 1
}

function check_webdav_cli_running() {
	webdav_cli_PID=$(ps -ef | grep -v "grep" | grep "webdav-cli" | awk '{print $2}')
}

function set_webdav_port() {

	while true
	do

		echo -e "请输入要设置的WebDAV 端口 (1-65535)"
		echo -e "${Tip}22 80 443  8080  1080  等等不要设置"
		echo -e "${Tip}默认端口: ${default_webdav_port}" && echo
		read -e -p "(输入端口号 默认: ${default_webdav_port}):" webdav_port
		if [[ -z "$webdav_port" ]]; then
			webdav_port=${default_webdav_port}
			echo && echo ${full_line} && echo -e "	端口 : ${Green_font_prefix}${webdav_port}${Font_color_suffix}" && echo ${full_line} && echo
			break
		fi
	
		#check webdav_port
		expr $webdav_port + 1 &>/dev/null
		if [[ $? != 0 ]]; then
			echo -e "${Error} ${Red_font_prefix}你输入的不是纯数字(1-65535)${Font_color_suffix}"
			read -p "按回车键重新设置" && echo
			continue
		fi

		#判断输入的数字是否以0开头  
		if [[ `expr index  ${webdav_port} 0` == 1 ]];then
			echo -e "${Error} ${Red_font_prefix}不要以0开头${Font_color_suffix}"
			read -p "按回车键重新设置" && echo
			continue
		fi
		
		
		if [[ $? == 0 ]]; then
			#ge >=   le <=  判断是否在范围1-65535内
			if [[ ${webdav_port} -ge 1 ]] && [[ ${webdav_port} -le 65535 ]]; then
				echo && echo ${full_line} && echo -e "	端口 : ${Green_font_prefix}${webdav_port}${Font_color_suffix}" && echo ${full_line} && echo
				break
			else
				echo -e "${Error} ${Red_font_prefix}你输入的数字不在范围内(1-65535)${Font_color_suffix}"
				read -p "按回车键重新设置" && echo
			fi
		fi
	done

}

function set_username_and_pwd() {
	echo
	echo
	read -e -p "设置WebDAV 用户名：" webdav_user
	[[ -z ${webdav_user} ]] && echo "用户名不能为空！" && break

	echo ${full_line} && echo -e "WebDAV 用户名: ${Green_font_prefix}${webdav_user}${Font_color_suffix}" && echo ${full_line} && echo

	read -e -p "设置WebDAV 密码：" webdav_pwd
	[[ -z ${webdav_pwd} ]] && echo "密码不能为空！" && break
	echo ${full_line} && echo -e "WebDAV 密码: ${Green_font_prefix}${webdav_pwd}${Font_color_suffix}" && echo ${full_line} && echo

}

#public network ip
function get_public_ip() {
	public_ip=$(wget -qO- -t1 -T2 ipinfo.io/ip)
	if [[ -z "${public_ip}" ]]; then
		public_ip=$(wget -qO- -t1 -T2 api.ip.sb/ip)
		if [[ -z "${ip}" ]]; then
			public_ip=$(wget -qO- -t1 -T2 members.3322.org/dyndns/getip)
			if [[ -z "${ip}" ]]; then
				# public_ip="您服务器的公网IP"
				echo -e "${Error}：未获取到服务器公网IP" && break
			fi
		fi
	fi
}

function get_private_ip() {
	private_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")
}

function start_webdav() {
	check_webdav_cli_running
	get_webdav_config
	if [[ -z ${webdav_cli_PID} ]]; then
		echo -e "开始启动webdav-cli"
		[[ ! -e $note_sync_dir ]] && mkdir -p $note_sync_dir

		echo -e "nohup $base_folder/node/bin/webdav-cli --path $note_sync_dir --host $private_ip_from_jq --port $webdav_port_from_jq --username $webdav_user_from_jq --password $webdav_pwd_from_jq --rights $webdav_rigts >$webdav_log_file 2>&1 &"
		nohup $base_folder/node/bin/webdav-cli --path $note_sync_dir --host $private_ip_from_jq --port $webdav_port_from_jq --username $webdav_user_from_jq --password $webdav_pwd_from_jq --rights $webdav_rigts >$webdav_log_file 2>&1 &
		check_webdav_cli_running
		
		if [[ -z ${webdav_cli_PID}  ]]; then
			echo -e "启动webdav-cli失败"
		else
			echo -e "启动webdav-cli成功"
		fi
		
	fi

}

function stop_webdav() {
	check_webdav_cli_running
	if [[ -z ${webdav_cli_PID} ]]; then
		echo -e "${Tip}${Info_font_prefix}[信息]${Font_suffix}  关闭成功 "
	else
		kill -9 ${webdav_cli_PID}

		if [[ $? -eq 0 ]]; then
			echo -e "${Tip}${Info_font_prefix}[信息]${Font_suffix}  关闭成功 !"
		else
			echo -e "${Error_font_prefix}[错误]${Font_suffix} 关闭失败 !"
		fi
	fi
}

function restart_webdav() {
	stop_webdav && start_webdav
}

function uninstall_webdav() {
	check_root
	stop_webdav

	[[ ! -e ${webdav_config_file} ]] && [[ ! -e ${base_folder}/node ]] && echo -e "${Error} 并未安装webdav-cli" && exit 1
	echo "确定要 卸载webdav-cli？[y/n]" && echo
	read -e -p "(默认: n):" unyn
	[[ -z ${unyn} ]] && unyn="n"
	if [[ ${unyn} == [Yy] ]]; then

		check_webdav_cli_running && [[ ! -z "${webdav_cli_PID}" ]] && kill -9 ${webdav_cli_PID}

		rm -rf ${base_folder}/node && rm -rf /usr/bin/node && rm -rf $jq_folder
		if [[ -e ${base_folder}/node ]] || [[ -e /usr/bin/node ]] || [[ -e $base_folder/jq ]] || [[ -e ~/jq ]]; then
			echo -e "${Error}：卸载出现异常" && break
		else
			echo && echo "卸载webdav-cli完成！" && echo
		fi
	else
		echo && echo " 已取消卸载..." && echo
	fi
}

# get linux type
get_linux_type() {
	if [[ -f /etc/redhat-release ]]; then
		release="centos"

	elif cat /etc/issue | grep -q -E -i "debian"; then
		release="debian"
	elif cat /etc/issue | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
	elif cat /proc/version | grep -q -E -i "debian"; then
		release="debian"
	elif cat /proc/version | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
	fi

	bit=$(uname -m)
	echo -e " ${Green_background_prefix}当前Linux版本:${release}${Font_color_suffix}"
	echo -e " ${Green_background_prefix}系统类型：${bit}${Font_color_suffix}"
}

function install_git() {
	while true; do
		if [[ -z $(git --version) ]]; then
			echo "${full_line} 没有检测到系统安装了git，开始安装git${full_line}" && echo
			if [[ ${release} == "centos" ]]; then
				yum install -y git
			else
				apt-get install -y git
			fi
		else
			echo "${full_line} git安装完成！${full_line}" && echo
			break
		fi
	done
}

#install jq
function install_jq() {
    get_linux_type
    
	if [[ -z $(git --version) ]]; then
		install_git
	fi
	cd $base_folder
	git clone ${jq_down_link}

	
	if [[ ${bit} = "x86_64" ]]; then
		mv $jq_folder/jq-linux64 ${jq_file}
	else
		mv $jq_folder/jq-linux32 ${jq_file}
	fi

	chmod +x ${jq_file}
	[[ ! -e ${jq_file} ]] && echo -e "${Error} ${Red_font_prefix}JQ解析器$({jq_file}) 剪切失败，请检查 ! ${Font_color_suffix}" && exit 1
	[[ -e ${jq_file} ]] && echo -e "${Info}${Green_font_prefix}JQ解析器剪切成功！${Font_color_suffix}"

}

function stop_firewall() {
	echo -e "关闭防火墙中..."
	systemctl stop firewalld.service
}

function get_webdav_config() {

	if [[ ! -e ${jq_file} ]]; then
		install_jq
	fi

	#get config info
	public_ip_from_jq=$(${jq_file} '.public_ip' ${webdav_config_file} | sed 's/^.//;s/.$//')
	private_ip_from_jq=$(${jq_file} '.private_ip' ${webdav_config_file} | sed 's/^.//;s/.$//')

	webdav_port_from_jq=$(${jq_file} '.webdav_port' ${webdav_config_file})
	webdav_user_from_jq=$(${jq_file} '.webdav_user' ${webdav_config_file} | sed 's/^.//;s/.$//')
	webdav_pwd_from_jq=$(${jq_file} '.webdav_pwd' ${webdav_config_file} | sed 's/^.//;s/.$//')

}

function view_webdav_cofig() {
	check_webdav_cli_installtation_status
	get_webdav_config

	#ouput config info
	echo && echo "==================================================="
	echo -e " WebDAV配置信息：" && echo
	echo -e " WebDAV URL\t    : ${Green_font_prefix}http://${public_ip_from_jq}:${webdav_port_from_jq}${Font_color_suffix}"
	echo -e " WebDAV用户名\t    : ${Green_font_prefix}${webdav_user_from_jq}${Font_color_suffix}"
	echo -e " WebDAV密码\t    : ${Green_font_prefix}${webdav_pwd_from_jq}${Font_color_suffix}"
	echo -e " WebDAV权限\t    : ${Green_font_prefix}${webdav_rigts}${Font_color_suffix}" && echo

	echo "--------------------------------"
	echo -e " 公网IP\t    : ${Green_font_prefix}${public_ip_from_jq}${Font_color_suffix}"
	echo -e " 私有IP\t    : ${Green_font_prefix}${private_ip_from_jq}${Font_color_suffix}"

	echo && echo "==================================================="

}

function check_wedav_cli_status() {
	if [[ -e ${webdav_config_file} ]] && [[ -e ${base_folder}/node ]]; then
		webdav_PID=$(ps -ef | grep -v "grep" | grep "webdav-cli" | awk '{print $2}')
		if [[ ! -z "${webdav_PID}" ]]; then
			echo -e " webdav-cli状态: ${Green_font_prefix}已安装${Font_color_suffix} 并 ${Green_font_prefix}已启动${Font_color_suffix}"
		else
			echo -e " webdav-cli状态: ${Green_font_prefix}已安装${Font_color_suffix} 并 ${Red_font_prefix}未启动${Font_color_suffix}"
		fi
	else
		echo -e " webdav-cli状态: ${Red_font_prefix}未安装${Font_color_suffix}"
	fi
}

function check_firewall_status() {
	if [[ ! -z $(systemctl status firewalld | grep dead) ]]; then
		echo -e " 防火墙状态：${Green_font_prefix}已关闭${Font_color_suffix}"
	elif [[ ! -z $(systemctl status firewalld | grep running) ]]; then
		echo -e " 防火墙状态：${Red_font_prefix}开启（建议关闭）${Font_color_suffix}"
	fi
}





# Lowercase character
lowStr="abcdefghijklmnopqrstuvwxyz"

upperStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# special character
specialStr="~!@#$%()_+-[]"

# number
numStr="0123456789"

# 随机获取字符串字符
function getRandomChar() {
    local string=$1
    # echo 字符串：$string

    getStrLength $string
    local strLength=$?
    # echo 字符串长度：$strLength

    generateRand $strLength

    index=$(($random_number - 1))
    # echo "index=$index"
    randowm_char=${string:($index):1}
    # echo 随机的字符：$randowm_char
}

#----------------------------------------字符随机生成函数----------------------------------------
# 随机获取小写字符
function getRandLowChar() {
    getRandomChar $lowStr
    # echo -e "小写字符：$randowm_char"
}

#随机获取大写字符
getRandUpperChar() {
    getRandomChar $upperStr
    # echo -e "大写字符：$randowm_char"
}

#随机获取数字字符
getRandNum() {
    getRandomChar $numStr
    # echo -e "数字：$randowm_char"
}

#随机获取特殊字符
getRandSpecialChar() {
    getRandomChar $specialStr
    # echo -e "特殊字符：$randowm_char"
}
#----------------------------------------字符随机生成函数----------------------------------------

function getStrLength() {
    return $(expr length $1)
}

# 随机生成1~指定数这个范围的数字
generateRand() {
    randomRange 1 $1
}

# 生成指定范围的数字(min,max)
randomRange() {
    min=$1
    max=$(($2 - $min + 1))
    #时间戳（精确到纳秒）
    # num=$(date +%s%N)
    #系统随机值
    num=$RANDOM
    random_number=$(($num % $max + $min))
    # echo 随机数=$random_number

}

#遍历数组
foreach_arr() {
    # echo -e "数组遍历"
    for item in "${arr_str[@]}"; do
        echo "${item}"
    done

}

#随机调用其中一个字符随机生成函数
randomInvoke() {
    case "$1" in
    1)
        getRandLowChar
        ;;
    2)
        getRandUpperChar
        ;;
    3)
        getRandNum
        ;;
    *)
        getRandSpecialChar
        ;;
    esac

}

#打乱排序：循环随机位交换法
#原理：
# 循环遍历该数组，在每次遍历中产生一个0 ~ length - 1的数，该数代表本次循环要随机交换的位置。
# 将本次循环当前位置的数和随机位置的数进行交换
random_sort() {
    length=${#arr_str[*]}
    for ((i = 0; i < $length; i++)); do
        generateRand $length
        randomIndex=$(($random_number - 1))

        currentelementValue=${arr_str[i]}
        # echo "currentelementValue $currentelementValue"
        arr_str[i]=${arr_str[${randomIndex}]}
        arr_str[${randomIndex}]=${currentelementValue}
    done
}


arrayToString() {
    # echo -e "传来的参数：" $@
    new_arr=($@)
    randomPwd=''
    for i in ${new_arr[@]}; do
        randomPwd=$randomPwd$i
    done

}

#生成随机密码(指定密码长度)
getRandomPwd() {
    while true; do
        #判断密码长度
        if [ $1 -ge 8 ] && [ $1 -le 20 ]; then
            echo -e "你设置的密码长度为：$1"
            break
        else
            echo -e "密码长度需要在8~20位！" && exit
        fi
    done

    pwd_length=$1

    #定义空数组
    arr_str=()

    #先把 4 种字符每种来一个，并添加到数组中
    getRandLowChar
    # echo -e "数组长度：${#arr_str[*]}"

    arr_str[${#arr_str[*]}]=g

    getRandUpperChar
    arr_str[${#arr_str[*]}]=$randowm_char

    getRandNum
    arr_str[${#arr_str[*]}]=$randowm_char

    getRandSpecialChar
    arr_str[${#arr_str[*]}]=$randowm_char

    # echo -e "第1次打印数组"
    echo ${arr_str[*]}
    # echo -e "第1次遍历数组"
    foreach_arr

    # 因为已经把 4 种字符放进数组了，所以 i 取值从 4开始
    for ((i = 4; i < ${pwd_length}; i++)); do
        generateRand 4
        randomInvoke $random_number
        arr_str[${#arr_str[*]}]=$randowm_char
    done

    # echo -e "第2次打印数组"
    echo ${arr_str[@]}
    # echo -e "第2次遍历数组"
    foreach_arr

    #打乱排序
    random_sort
    # echo -e "打乱排序后：" && echo ${arr_str[*]}

    #将数组转字符串
    arrayToString ${arr_str[@]}

    echo -e "随机密码 $randomPwd"
}


function default_install_webdav_cli(){
	webdav_user=$(openssl rand -hex 3)
	getRandomPwd 16
	webdav_pwd=$randomPwd
	webdav_port=1900

	# install node
	wget $node_down_link -O $base_folder/node.tar.xz
	mkdir -p $base_folder/node &
	tar xvfJ $base_folder/node.tar.xz -C $base_folder/node --strip-components 1

	# Add soft link
	ln -s $base_folder/node/bin/node /usr/bin/node

	# install webdav-cli
	$base_folder/node/bin/npm install --global webdav-cli

	get_public_ip
	get_private_ip
	write_webdav_config

	# run webdav-cli
	start_webdav

	stop_firewall
	view_webdav_cofig

}

function my_start() {
	echo -e "一键管理脚本 ${Green_background_prefix}[v1.0]${Font_color_suffix}
  ${Green_font_prefix}1.${Font_color_suffix} 安装webdav-cli并启动
  ${Green_font_prefix}2.${Font_color_suffix} 卸载webdav-cli 
  ${Green_font_prefix}3.${Font_color_suffix} 关闭webdav-cli 
  ${Green_font_prefix}4.${Font_color_suffix} 开启webdav-cli 
  ${Green_font_prefix}5.${Font_color_suffix} 重启webdav-cli 
  
————————————————————————————————————————————————————————————————
  ${Green_font_prefix}6.${Font_color_suffix} 修改配置信息
  ${Green_font_prefix}7.${Font_color_suffix} 查看webdav-cli配置信息
  ${Green_font_prefix}8.${Font_color_suffix} 查看webdav-cli日志
  

  "
	check_wedav_cli_status
	check_firewall_status
	echo && read -e -p "请输入数字 [1-8]：" num
	case "${num}" in
	1)
		install_and_start_webdav
		;;
	2)
		uninstall_webdav
		;;
	3)
		stop_webdav
		;;
	4)
		start_webdav
		;;
	5)
		restart_webdav
		;;
	6)
		modify_webdav_config
		;;
	7)
		view_webdav_cofig
		;;
	8)
		# view log
		tail -f $webdav_log_file
		;;
	*)
		clear
		echo -e "${Error} 请输入正确的数字 [1-8]"
		;;
	esac
}

# 默认安装并启动webdav_cli，全自动
if [[ $1 -eq 1 ]]; then
	default_install_webdav_cli && exit
fi

my_start
